package com.example.blades.diary;

import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;


import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;


public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    Button btn_createDB=null;
    Intent intent;
    List<Note> all= LitePal.findAll(Note.class);
    List<Map<String,Object>> listItem=new ArrayList<Map<String,Object>>();
    SimpleAdapter mySimpleAdapter;
    ListView listview;
    private TextView emptyview;
    final String ACTION_EDIT="EDIT";
    final String ACTION_NEW="NEW";
    long curID;
    private Boolean isFirst=Boolean.TRUE;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.v("START","启动");

        emptyview=(TextView) findViewById(R.id.empty_view);
        listview = (ListView) findViewById(R.id.listview);
        LitePal.getDatabase();


        /*bug：删除全部数据后，再重新插入数据闪退，到数据库中查找过，确实存在数据，说明插入操作已成功，但页面打不开
        * 目前已经找到原因，是因为litepal数据库的id自增问题，如插入了两条数据，id分别为1、2，但是把这两条数据删除后，
        * 继续插入一条新数据，此时id为3。。。
        * 已解决*/

        /*没有数据*/
        if(all.isEmpty())
        {
            Log.v("Notice","all is empty");
            listview.setEmptyView(emptyview);

        }
        else
        {
            Log.v("Notice","all is not empty");
            emptyview.setVisibility(View.INVISIBLE);
            listview=null;
            InitList();
            Log.v("INIT"," InitList()");
        }


        btn_createDB=(Button)findViewById(R.id.button);

        FloatingActionButton btn_float=(FloatingActionButton)findViewById(R.id.floatingActionButton);
        btn_float.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent=new Intent(MainActivity.this,DiaryEditor.class);
                Bundle bundle0=new Bundle();
                bundle0.putString("action",ACTION_NEW);
                intent.putExtras(bundle0);
                intent.setClass(MainActivity.this,DiaryEditor.class);
                startActivity(intent);
                MainActivity.this.finish();

            }
        });

        btn_createDB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this,"HelloDiary",Toast.LENGTH_SHORT).show();

            }
        });
//
////         添加长按点击弹出选择菜单
//        listview.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
//            public void onCreateContextMenu(ContextMenu menu, View v,
//                                            ContextMenu.ContextMenuInfo menuInfo) {
//                /*获取长按的item对象*/
////
////                Log.v("Number",String.valueOf(listview.getId()));
////                listview.getItemAtPosition()
//                menu.add(0, 0,0, "删除");
//            }
//        });

    }
//
//    //给菜单项添加事件
//    @Override
//    public boolean onContextItemSelected(MenuItem item) {
//        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        /*info.id得到listview中选择的条目绑定的id*/
//        LitePal.delete(Note.class,curID);
//        String cur = ((TextView)info.targetView.findViewById(R.id.curID)).getText().toString();
////        Toast.makeText(MainActivity.this,"内容为:" + cur,Toast.LENGTH_LONG).show(); // 显示那条数据
////        String section =String.valueOf(item.get("curID").toString());//取得存到list里面的curID，即数据库中数据的id
//        int itemSelectedID=Integer.valueOf(cur);/*ListView的Id*/
////        Toast.makeText(MainActivity.this,"内容为:" + cur,Toast.LENGTH_LONG).show();
//        long curid=(long)itemSelectedID;
//
//
//        switch (item.getItemId()) {
//            case 0:
////                listview.removeView(info.targetView.findViewById(R.id.curID));
////                LitePal.delete(Note.class,curid);
//                //System.out.println("删除"+info.id);
//
//                Toast.makeText(this,"已删除",Toast.LENGTH_LONG).show();  //删除事件的方法
////                refresh();
//                return true;
//            default:
//                return super.onContextItemSelected(item);
//        }
//    }

    private void InitList() {
        Log.v("TAG","InitList");
        Log.v("ALL",String.valueOf(all.size()));

            /*获取数据库中第一条数据的id*/
            curID=LitePal.findFirst(Note.class).getId();
            for (int i =(int)curID; i < all.size()+(int)curID; i++)
            {
                isFirst = Boolean.FALSE;
                Log.v("ALL", String.valueOf(i));
                Note note = LitePal.find(Note.class, i);
                Log.v("TAG", "Note" + i + "   " + note.getId() + " " + note.getTitle() + "  " + note.getDate());
                Log.v("TAG", "InitLial Note");
                Map<String, Object> noteItem = new HashMap<String, Object>();
                Log.v("TAG", "InitLial Map");
                noteItem.put("title", note.getTitle());
                Log.v("TAG", "InitLial put note title");
                noteItem.put("date", note.getDate());
                noteItem.put("curID",note.getId());
                listItem.add(noteItem);
                Log.v("TAG", "ListItem Put");
            }

        Log.v("TAG",listItem.get(0).toString());

        mySimpleAdapter=new SimpleAdapter(
                this,
                listItem,
                R.layout.card_view,
                new String[] {"curID","title","date"},
                new int[] {R.id.curID,R.id.title_row,R.id.date_row});

        Log.v("TAG","Init simpleAdapter");
        listview=(ListView)findViewById(R.id.listview);
        Log.v("TAG","Init find R.id.list");
        listview.setAdapter(mySimpleAdapter);
        Log.v("TAG","InitList success");
        listview.setOnItemClickListener(this);
    }


    /*点击事件*/
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {/*通过view获取其内部的组件，进而进行操作*/
        Intent intent = new Intent(this, DiaryEditor.class);
        Log.v("TAG","Init intent");
        HashMap item = (HashMap)parent.getItemAtPosition(position);
        String section =String.valueOf(item.get("curID").toString());//取得存到list里面的curID，即数据库中数据的id
        int curID=Integer.valueOf(section);
        int idx=new Long(id).intValue();/*ListView的Id*/
        all.get(idx);
        Log.v("Tag curID",String.valueOf(curID));

        Bundle bundle = new Bundle();
        Log.v("TAG","Init bundle");

        bundle.putLong("id", curID);
        Log.v("Tag id:",String.valueOf(curID));
        bundle.putString("action",ACTION_EDIT);
        intent.putExtras(bundle);
        intent.setClass(MainActivity.this,DiaryEditor.class);
        startActivity(intent);
        MainActivity.this.finish();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.delete_sub, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.deleteAll:
                LitePal.deleteAll(Note.class);
                MainActivity.this.finish();
                Toast.makeText(this, "已删除全部日记！", Toast.LENGTH_SHORT).show();
                Log.v("Delete","已删除全部日记！");
                refresh();
                break;
            default:
        }
        return true;
    }


    /**
     * 刷新主界面
     */
    private void refresh() {
        finish();
        Intent intent = new Intent(MainActivity.this, MainActivity.class);
        startActivity(intent);
    }

}

